package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.service.ex.*;
import org.springframework.web.bind.annotation.ExceptionHandler;
import util.JsonResult;

import javax.servlet.http.HttpSession;

/**控制层基类*/
public class BaseController {
    //操作成功状态码
    public static final int Ok = 200;

    //请求处理方法，这个方法的返回值就是需要传递给前端的数据
    //当项目产生异常时，被统一拦截到此方法中
    @ExceptionHandler({ServiceException.class,FileUploadException.class})//统一处理抛出的异常
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        if(e instanceof UsernameDuplicatedException){
            result.setMessage("名字已被占用");
            result.setState(4000);
        }else if(e instanceof UserNotFoundException){
            result.setMessage("用户数据不存在异常");
            result.setState(5001);
        }else if(e instanceof PasswordNotMatchException){
            result.setMessage("密码错误异常");
            result.setState(5002);
        }else if(e instanceof InsertException){
            result.setMessage("产生未知异常");
            result.setState(5000);
        }else if(e instanceof UpdateException){
            result.setMessage("更新数据时产生未知异常");
            result.setState(5003);
        }else if (e instanceof FileEmptyException) {
            result.setState(6000);
        } else if (e instanceof FileSizeException) {
            result.setState(6001);
        } else if (e instanceof FileTypeException) {
            result.setState(6002);
        } else if (e instanceof FileStateException) {
            result.setState(6003);
        } else if (e instanceof FileUploadIOException) {
            result.setState(6004);
        }else if(e instanceof AddressCountLimitException){
            result.setMessage("用户收货地址超出上限异常");
            result.setState(4003);
        }else if(e instanceof AddressNotFoundException){
            result.setMessage("用户收货地址不存在");
            result.setState(4004);
        }else if(e instanceof AccessDeniedException){
            result.setMessage("非法数据访问");
            result.setState(4005);
        }else if(e instanceof DeleteException){
            result.setMessage("删除数据时产生未知异常");
            result.setState(4006);
        }else if(e instanceof ProductNotFoundException){
            result.setMessage("产品未找到异常");
            result.setState(4007);
        }else if(e instanceof CartNotFoundException){
            result.setMessage("购物车商品未找到异常");
            result.setState(4008);
        }

        return  result;
    }

    //获取当前用户session对象中的uid
    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }
    //获取当前用户session对象中的username
    protected  final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }


}
